﻿using DevExpress.Utils;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.mMachine.BLL;
using Lamex.mMachine.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mMachine.UI
{
    public partial class frmMAC_Equipment_Basic_Info : frmBaseDataForm
    {
        static DataTable dtComlist = new DataTable();
        static Common.GetDataTable comm = new Common.GetDataTable();
        public frmMAC_Equipment_Basic_Info()
        {
            InitializeComponent();
            InitializeForm();
            dtComlist = comm.GetValuesOption();
            //加载下拉框值
            ComboxList_MACHINE_TYPE();
            ComboxList_EDIT_MACHINE_LEVEL();
            ComboxList_MACHINE_ORIGIN();
            GetSearchLookUpEdit_MachineNo();
        }
        protected override void InitializeForm()
        {
            _SummaryView = new DevGridView(gridView1);
            gridView1.DoubleClick += new EventHandler(OnGridViewDoubleClick); //主表DoubleClict
            frmGridViewCust.RegisterGrid(gridView1);
            DevStyle.SetGridControlLayout(gridControl1, false);//表格设置   

            DevStyle.SetSummaryGridViewLayout(gridView1);
            DevStyle.SetDetailGridViewLayout(gridView1);
            ShowSummary(); //下载显示数据.
            tpSummary = xtraTabPage1;
            tcBusiness = xtraTabControl1;
            tpSummary.PageVisible = true;
            //tpDetail.PageVisible = false;
            tcBusiness.ShowTabHeader = DefaultBoolean.True;
            tcBusiness.SelectedTabPage = tpSummary;
        }
        private void ShowSummary()
        {
            try
            {
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            string sqlWhere = "";
            string sql = @"SELECT [MACHINE_NO]
      ,[MACHINE_APPLIED_NO]
      ,[MACHINE_SN]
      ,[MACHINE_NAME]
      ,[MACHINE_DESC]
      ,[MACHINE_TYPE]
      ,[MACHINE_LEVEL]
      ,[MACHINE_BRAND]
      ,[MACHINE_POWER]
      ,[MACHINE_ORIGIN]
      ,CONVERT(VARCHAR(10),ONSITE_DATE,120) ONSITE_DATE
      ,CONVERT(VARCHAR(10),DEBUGGING_DATE,120) DEBUGGING_DATE
      ,CONVERT(VARCHAR(10),TRIAL_RUN_DATE,120) TRIAL_RUN_DATE
      ,CONVERT(VARCHAR(10),TRAINING_DATE,120) TRAINING_DATE
      ,CONVERT(VARCHAR(10),ACCEPTANCE_DATE,120) ACCEPTANCE_DATE
      ,CONVERT(VARCHAR(10),COMMISSIONING_DATE,120) COMMISSIONING_DATE
      ,[UPDATE_TIME]
      ,[UPDATE_USER]
  FROM [LamexMESManager].[dbo].[FAMA_Account_Basic_Info] WHERE 1=1";
            if (!string.IsNullOrEmpty(txtMACHINE_NO.Text))
            {
                sqlWhere += " and MACHINE_NO like '%" + txtMACHINE_NO.Text + "%'";
            }
            if (!string.IsNullOrEmpty(txtMACHINE_ORIGIN.Text))
            {
                sqlWhere += " and MACHINE_ORIGIN like '%" + txtMACHINE_ORIGIN.Text + "%'";
            }
            if (!string.IsNullOrEmpty(txtMACHINE_TYPE.Text))
            {
                sqlWhere += " and MACHINE_TYPE like '%" + txtMACHINE_TYPE.Text + "%'";
            }

            sql = sql + sqlWhere+ " order by UPDATE_TIME desc ";
            DataTable dt = BaseFactory<FAMA_Account_Basic_Info>.Instance.GetDataTableBySql(sql);
            DoBindingSummaryGrid(dt);
            gridView1.BestFitColumns();
            this.gridView1.OptionsView.ColumnAutoWidth = false;
            base.DoView(sender);

        }

        private void frmMAC_Equipment_Basic_Info_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        //新增
        public override void DoAdd(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            // if (!BuildSqlHelper.IsExistList("FAMA_Account_Basic_Info")) return;
            #endregion
            // xtraTabPage1.PageEnabled = false;
            Initiallize();
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            //获取流水号
            GetSearchLookUpEdit();
            EDIT_MACHINE_NO.Text = Common.SerialNoHelper.Generate();
            IsEdit = "Add";
            base.DoAdd(sender);
        }
        public void GetSearchLookUpEdit()
        {
            string sql = @"  SELECT MACHINE_APPLIED_NO,APPLIED_USER FROM [LamexMESManager].[dbo].[FAMA_Account_Purchase_plan]";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            EDIT_MACHINE_APPLIED_NO.Properties.ValueMember = "MACHINE_APPLIED_NO";
            EDIT_MACHINE_APPLIED_NO.Properties.DisplayMember = "MACHINE_APPLIED_NO";
            EDIT_MACHINE_APPLIED_NO.Properties.DataSource = dt;
        }
        public void GetSearchLookUpEdit_MachineNo()
        {
            string sql = @" SELECT MACHINE_NO,MACHINE_NAME,MACHINE_DESC FROM [LamexMESManager].[dbo].[FAMA_Account_Basic_Info]";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);   
            txtMACHINE_NO.Properties.ValueMember = "MACHINE_NO";
            txtMACHINE_NO.Properties.DisplayMember = "MACHINE_NO";
            txtMACHINE_NO.Properties.DataSource = dt;
        }
        //获取流水号和下拉值
        //public void AddInitialize()
        //{
        //    EDIT_MACHINE_NO.Text = Common.SerialNoHelper.Generate();
        //    ComboxList_MACHINE_TYPE();
        //    ComboxList_EDIT_MACHINE_LEVEL();
        //    ComboxList_MACHINE_ORIGIN();
        //}
        //初始化新增信息
        public void Initiallize()
        {
            EDIT_MACHINE_NO.Text = "";//设备编号
            EDIT_MACHINE_APPLIED_NO.Text = "";//申购编号
            EDIT_MACHINE_SN.Text = "";//设备型号
            EDIT_MACHINE_NAME.Text = "";//设备名称
            EDIT_MACHINE_DESC.Text = "";//设备描述
            EDIT_MACHINE_TYPE.Text = "";//设备类别
            EDIT_MACHINE_LEVEL.Text = "";//设备等级
            EDIT_MACHINE_BRAND.Text = "";//设备品牌
            EDIT_MACHINE_POWER.Text = "";//设备功率
            EDIT_MACHINE_ORIGIN.Text = "";//设备产地
            EDIT_ONSITE_DATE.Text = "";//设备到厂时间
            EDIT_DEBUGGING_DATE.Text = "";//调试完成时间
            EDIT_TRIAL_RUN_DATE.Text = "";//试产完成时间
            EDIT_TRAINING_DATE.Text = "";//培训完成时间
            EDIT_ACCEPTANCE_DATE.Text = "";//设备验收时间
            EDIT_COMMISSIONING_DATE.Text = "";//设备投产时间
            IsEdit = "";
        }
        //编辑
        public override void DoEdit(Lamex.Interface.IButtonInfo sender)
        {
            if (gridView1.SelectedRowsCount == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("【没有选中要修改的数据！】", "提示", MessageBoxButtons.OK);
                return;
            }
            int m = gridView1.FocusedRowHandle;
            DataRow dr = gridView1.GetDataRow(m);
            KeysName = dr["MACHINE_NO"].ToString();
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            IsEdit = "Edit";
            GetSearchLookUpEdit();

            //加载数据
            EDIT_MACHINE_NO.Text = dr["MACHINE_NO"].ToString();//设备编号
            EDIT_MACHINE_APPLIED_NO.Text = dr["MACHINE_APPLIED_NO"].ToString();//申购编号
            EDIT_MACHINE_SN.Text = dr["MACHINE_SN"].ToString();//设备型号
            EDIT_MACHINE_NAME.Text = dr["MACHINE_NAME"].ToString();//设备名称
            EDIT_MACHINE_DESC.Text = dr["MACHINE_DESC"].ToString();//设备描述
            EDIT_MACHINE_TYPE.Text = dr["MACHINE_TYPE"].ToString();//设备类别
            EDIT_MACHINE_LEVEL.Text = dr["MACHINE_LEVEL"].ToString();//设备等级
            EDIT_MACHINE_BRAND.Text = dr["MACHINE_BRAND"].ToString();//设备品牌
            EDIT_MACHINE_POWER.Text = dr["MACHINE_POWER"].ToString();//设备功率
            EDIT_MACHINE_ORIGIN.Text = dr["MACHINE_ORIGIN"].ToString();//设备产地
            EDIT_ONSITE_DATE.Text = dr["ONSITE_DATE"].ToString();//设备到厂时间
            EDIT_DEBUGGING_DATE.Text = dr["DEBUGGING_DATE"].ToString();//调试完成时间
            EDIT_TRIAL_RUN_DATE.Text = dr["TRIAL_RUN_DATE"].ToString();//试产完成时间
            EDIT_TRAINING_DATE.Text = dr["TRAINING_DATE"].ToString();//培训完成时间
            EDIT_ACCEPTANCE_DATE.Text = dr["ACCEPTANCE_DATE"].ToString();//设备验收时间
            EDIT_COMMISSIONING_DATE.Text = dr["COMMISSIONING_DATE"].ToString();//设备投产时间     
            base.DoEdit(sender);
        }
        //保存
        public override void DoSave(Lamex.Interface.IButtonInfo sender)
        {
            try
            {
                if(string.IsNullOrEmpty(EDIT_MACHINE_SN.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("设备型号不能为空", "提示", MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_MACHINE_NAME.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("设备名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_MACHINE_DESC.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("设备描述不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_MACHINE_BRAND.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("设备品牌不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                FAMA_Account_Basic_InfoInfo model = new FAMA_Account_Basic_InfoInfo();
                model.MACHINE_NO = EDIT_MACHINE_NO.Text;//设备编号
                model.MACHINE_APPLIED_NO = EDIT_MACHINE_APPLIED_NO.Text;//申购编号
                model.MACHINE_SN = EDIT_MACHINE_SN.Text;//设备型号
                model.MACHINE_NAME = EDIT_MACHINE_NAME.Text;//设备名称
                model.MACHINE_DESC = EDIT_MACHINE_DESC.Text;//设备描述
                model.MACHINE_TYPE = EDIT_MACHINE_TYPE.Text;//设备类别
                model.MACHINE_LEVEL = EDIT_MACHINE_LEVEL.Text;//设备等级
                model.MACHINE_BRAND = EDIT_MACHINE_BRAND.Text;//设备品牌
                model.MACHINE_POWER = Convert.ToDecimal(EDIT_MACHINE_POWER.Text.Length > 0 ? EDIT_MACHINE_POWER.Text : null);//设备功率
                model.MACHINE_ORIGIN = EDIT_MACHINE_ORIGIN.Text;//设备产地
                model.ONSITE_DATE = EDIT_ONSITE_DATE.Text.Length > 0 ? EDIT_ONSITE_DATE.Text : null;//设备到厂时间
                model.DEBUGGING_DATE = EDIT_DEBUGGING_DATE.Text.Length > 0 ? EDIT_DEBUGGING_DATE.Text : null;//调试完成时间
                model.TRIAL_RUN_DATE = EDIT_TRIAL_RUN_DATE.Text.Length > 0 ? EDIT_TRIAL_RUN_DATE.Text : null;//试产完成时间
                model.TRAINING_DATE = EDIT_TRAINING_DATE.Text.Length > 0 ? EDIT_TRAINING_DATE.Text : null;//培训完成时间
                model.ACCEPTANCE_DATE = EDIT_ACCEPTANCE_DATE.Text.Length > 0 ? EDIT_ACCEPTANCE_DATE.Text : null;//设备验收时间
                model.COMMISSIONING_DATE = EDIT_COMMISSIONING_DATE.Text.Length > 0 ? EDIT_COMMISSIONING_DATE.Text : null;//设备投产时间
                model.UPDATE_TIME = DateTime.Now;//创建时间
                model.UPDATE_USER = Lamex.Common.Loginer.CurrentUser.Account;//修改人
                if (IsEdit == "Add")
                {
                    if (BaseFactory<FAMA_Account_Basic_Info>.Instance.InsertKey(model))
                        DevExpress.XtraEditors.XtraMessageBox.Show("新增成功", "提示", MessageBoxButtons.OK);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("新增失败", "提示", MessageBoxButtons.OK);
                }
                if (IsEdit == "Edit")
                {
                    //if (BaseFactory<FAMA_Account_Basic_Info>.Instance.Update(model))
                    //采用直接更新方式，避免日期为空时显示1900-01-01
                    string STRONSITE = EDIT_ONSITE_DATE.Text.Length > 0 ? "'" + EDIT_ONSITE_DATE.Text + "'" : "NULL";
                    string STRDEBUGGING = EDIT_DEBUGGING_DATE.Text.Length > 0 ? "'" + EDIT_DEBUGGING_DATE.Text + "'" : "NULL";
                    string STRTRIAL_RUN = EDIT_TRIAL_RUN_DATE.Text.Length > 0 ? "'" + EDIT_TRIAL_RUN_DATE.Text + "'" : "NULL";
                    string STRTRAINING = EDIT_TRAINING_DATE.Text.Length > 0 ? "'" + EDIT_TRAINING_DATE.Text + "'" : "NULL";
                    string STRACCEPTANCE = EDIT_ACCEPTANCE_DATE.Text.Length > 0 ? "'" + EDIT_ACCEPTANCE_DATE.Text + "'" : "NULL";
                    string STRCOMMISSIONING = EDIT_COMMISSIONING_DATE.Text.Length > 0 ? "'" + EDIT_COMMISSIONING_DATE.Text + "'" : "NULL";


                    string sql = @"UPDATE  [LamexMESManager].[dbo].[FAMA_Account_Basic_Info] SET
       [MACHINE_APPLIED_NO]='" + model.MACHINE_APPLIED_NO + @"'
      ,[MACHINE_SN]='" + model.MACHINE_SN + @"'
      ,[MACHINE_NAME]='" + model.MACHINE_NAME + @"'
      ,[MACHINE_DESC]='" + model.MACHINE_DESC + @"'
      ,[MACHINE_TYPE]='" + model.MACHINE_TYPE + @"'
      ,[MACHINE_LEVEL]='" + model.MACHINE_LEVEL + @"'
      ,[MACHINE_BRAND]='" + model.MACHINE_BRAND + @"'
      ,[MACHINE_POWER]='" + model.MACHINE_POWER + @"'
      ,[MACHINE_ORIGIN]='" + model.MACHINE_ORIGIN + @"'
      ,[ONSITE_DATE]=" + STRONSITE + @"
      ,[DEBUGGING_DATE]=" + STRDEBUGGING + @"
      ,[TRIAL_RUN_DATE]=" + STRTRIAL_RUN + @"
      ,[TRAINING_DATE]=" + STRTRAINING + @"
      ,[ACCEPTANCE_DATE]=" + STRACCEPTANCE + @"
      ,[COMMISSIONING_DATE]=" + STRCOMMISSIONING + @"
      ,UPDATE_TIME=GETDATE()
      ,UPDATE_USER='" + Lamex.Common.Loginer.CurrentUser.Account + @"'
	  WHERE MACHINE_NO= '" + model.MACHINE_NO + "'";
                    if (BaseBuildSql.ExecuteNonQuery(sql) > 0)
                        DevExpress.XtraEditors.XtraMessageBox.Show("修改成功", "提示", MessageBoxButtons.OK);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("修改失败", "提示", MessageBoxButtons.OK);
                }
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
                DoView(null);
                Initiallize();
                base.DoSave(sender);

            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public override void DoExport(IButtonInfo sender)
        {
            if (!Directory.Exists(@"D:\MESTemp"))
                Directory.CreateDirectory(@"D:\MESTemp");
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.InitialDirectory = @"D:\MESTemp";//导出默认路径
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
            fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                //导出表【IE_Part_TaskList】中当前产品类型，无“工艺路线标识”的数据

                string sqlWhere = "";
                string sql = @"SELECT [MACHINE_NO]
      ,[MACHINE_APPLIED_NO]
      ,[MACHINE_SN]
      ,[MACHINE_NAME]
      ,[MACHINE_DESC]
      ,[MACHINE_TYPE]
      ,[MACHINE_LEVEL]
      ,[MACHINE_BRAND]
      ,[MACHINE_POWER]
      ,[MACHINE_ORIGIN]
      ,CONVERT(VARCHAR(10),ONSITE_DATE,120) ONSITE_DATE
      ,CONVERT(VARCHAR(10),DEBUGGING_DATE,120) DEBUGGING_DATE
      ,CONVERT(VARCHAR(10),TRIAL_RUN_DATE,120) TRIAL_RUN_DATE
      ,CONVERT(VARCHAR(10),TRAINING_DATE,120) TRAINING_DATE
      ,CONVERT(VARCHAR(10),ACCEPTANCE_DATE,120) ACCEPTANCE_DATE
      ,CONVERT(VARCHAR(10),COMMISSIONING_DATE,120) COMMISSIONING_DATE
      ,[UPDATE_TIME]
      ,[UPDATE_USER]
  FROM [LamexMESManager].[dbo].[FAMA_Account_Basic_Info] WHERE 1=1";
                if (!string.IsNullOrEmpty(txtMACHINE_NO.Text))
                {
                    sqlWhere += " and MACHINE_NO like '%" + txtMACHINE_NO.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtMACHINE_ORIGIN.Text))
                {
                    sqlWhere += " and MACHINE_ORIGIN like '%" + txtMACHINE_ORIGIN.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtMACHINE_TYPE.Text))
                {
                    sqlWhere += " and MACHINE_TYPE like '%" + txtMACHINE_TYPE.Text + "%'";
                }

                sql = sql + sqlWhere + " order by UPDATE_TIME desc ";
                DataTable dtList = BaseBuildSql.GetDataTableBySql(sql);

                GridControl grid = new GridControl();
                GridView view = new GridView();
                grid.ViewCollection.Add(view);
                grid.MainView = view;
                view.GridControl = grid;
                foreach (DataColumn dc in dtList.Columns)
                {
                    DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                    gridColumnNumber.FieldName = dc.ColumnName;
                }
                grid.DataSource = dtList;
                this.Controls.Add(grid);
                grid.ForceInitialize();//强制初始化
                //Font font = new Font("宋体", 11, FontStyle.Bold); 
                //view.Appearance.HeaderPanel.Font = font;
                //view.Appearance.Row.Font = font;            
                view.BestFitColumns();
                view.OptionsView.ColumnAutoWidth = false;
                view.OptionsView.ShowAutoFilterRow = false;
                view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                view.ExportToXlsx(fileDialog.FileName);
                if (DevExpress.XtraEditors.XtraMessageBox.Show("导出成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.FileName);//打开指定路径下的文件

            }
        }
        #region 下拉框信息
        public void ComboxList_MACHINE_TYPE()
        {
            DataTable dt = new DataTable();
            dt = dtComlist.Select("VALUE_NAME='设备类别'").CopyToDataTable();
            EDIT_MACHINE_TYPE.Text = "";
            EDIT_MACHINE_TYPE.Properties.Items.Clear();
            string[] values = dt.Rows[0]["VALUE_OPTION"].ToString().Split(';');
            foreach (var item in values)
            {
                EDIT_MACHINE_TYPE.Properties.Items.Add(item);
                txtMACHINE_TYPE.Properties.Items.Add(item);
            }
        }
        public void ComboxList_EDIT_MACHINE_LEVEL()
        {
            DataTable dt = new DataTable();
            dt = dtComlist.Select("VALUE_NAME='设备等级'").CopyToDataTable();
            EDIT_MACHINE_LEVEL.Text = "";
            EDIT_MACHINE_LEVEL.Properties.Items.Clear();
            string[] values = dt.Rows[0]["VALUE_OPTION"].ToString().Split(';');
            foreach (var item in values)
            {
                EDIT_MACHINE_LEVEL.Properties.Items.Add(item);
            }
        }
        public void ComboxList_MACHINE_ORIGIN()
        {
            DataTable dt = new DataTable();
            dt = dtComlist.Select("VALUE_NAME='设备产地'").CopyToDataTable();
            EDIT_MACHINE_ORIGIN.Text = "";
            EDIT_MACHINE_ORIGIN.Properties.Items.Clear();
            string[] values = dt.Rows[0]["VALUE_OPTION"].ToString().Split(';');
            foreach (var item in values)
            {
                EDIT_MACHINE_ORIGIN.Properties.Items.Add(item);
                txtMACHINE_ORIGIN.Properties.Items.Add(item);
            }
        }
        #endregion

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            DoEdit(null);
        }
    }
}
